package com.tracelog.example.service.impl;

import com.tracelog.core.annotation.TraceLog;
import com.tracelog.core.enums.LogLevel;
import com.tracelog.example.model.User;
import com.tracelog.example.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 用户服务实现
 *
 * @author tracelog
 * @since 1.0.0
 */
@Slf4j
@Service
@TraceLog(module = "用户服务", level = LogLevel.DEBUG)
public class UserServiceImpl implements UserService {

    private final Map<Long, User> userMap = new ConcurrentHashMap<>();
    private final AtomicLong idGenerator = new AtomicLong(1);

    /**
     * 模拟初始化数据
     */
    public UserServiceImpl() {
        User user1 = new User(idGenerator.getAndIncrement(), "admin", "admin123", "admin@example.com", "13800138000", 30);
        User user2 = new User(idGenerator.getAndIncrement(), "test", "test123", "test@example.com", "13800138001", 25);
        User user3 = new User(idGenerator.getAndIncrement(), "guest", "guest123", "guest@example.com", "13800138002", 18);
        
        userMap.put(user1.getId(), user1);
        userMap.put(user2.getId(), user2);
        userMap.put(user3.getId(), user3);
    }

    @Override
    public List<User> getAllUsers() {
        log.info("获取所有用户");
        return new ArrayList<>(userMap.values());
    }

    @Override
    public User getUserById(Long id) {
        log.info("获取ID为 {} 的用户", id);
        return userMap.get(id);
    }

    @Override
    @TraceLog("创建新用户")
    public User createUser(User user) {
        log.info("创建新用户: {}", user.getUsername());
        user.setId(idGenerator.getAndIncrement());
        userMap.put(user.getId(), user);
        return user;
    }

    @Override
    @TraceLog("更新用户信息")
    public User updateUser(User user) {
        log.info("更新ID为 {} 的用户", user.getId());
        if (!userMap.containsKey(user.getId())) {
            throw new RuntimeException("用户不存在");
        }
        userMap.put(user.getId(), user);
        return user;
    }

    @Override
    @TraceLog("删除用户")
    public void deleteUser(Long id) {
        log.info("删除ID为 {} 的用户", id);
        userMap.remove(id);
    }
} 